<template>
  <div class="login-container">
    <div class="login-box">
      <div class="logo-section">
        <h1>腾讯视频</h1>
        <p>精彩内容，尽在掌握</p>
      </div>

      <el-tabs v-model="activeTab" class="login-tabs" @tab-click="handleTabClick">
        <el-tab-pane label="用户登录" name="login">
          <el-form
            ref="loginFormRef"
            :model="loginForm"
            :rules="loginRules"
            label-width="0px"
            class="login-form"
          >
            <el-form-item prop="email">
              <el-input
                id="login-email"
                name="email"
                v-model="loginForm.email"
                placeholder="请输入邮箱"
                size="large"
                prefix-icon="User"
              />
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                id="login-password"
                name="password"
                v-model="loginForm.password"
                type="password"
                placeholder="请输入密码"
                size="large"
                prefix-icon="Lock"
                show-password
              />
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                size="large"
                class="login-button"
                :loading="loginLoading"
                @click="handleLogin"
              >
                登录
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <el-tab-pane label="用户注册" name="register">
          <el-form
            ref="registerFormRef"
            :model="registerForm"
            :rules="registerRules"
            label-width="0px"
            class="login-form"
          >
            <el-form-item prop="name">
              <el-input
                id="register-name"
                name="name"
                v-model="registerForm.name"
                placeholder="请输入用户名"
                size="large"
                prefix-icon="User"
              />
            </el-form-item>
            <el-form-item prop="email">
              <el-input
                id="register-email"
                name="email"
                v-model="registerForm.email"
                placeholder="请输入邮箱"
                size="large"
                prefix-icon="Message"
              />
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                id="register-password"
                name="password"
                v-model="registerForm.password"
                type="password"
                placeholder="请输入密码"
                size="large"
                prefix-icon="Lock"
                show-password
              />
            </el-form-item>
            <el-form-item prop="confirmPassword">
              <el-input
                id="register-confirm-password"
                name="confirmPassword"
                v-model="registerForm.confirmPassword"
                type="password"
                placeholder="请确认密码"
                size="large"
                prefix-icon="Lock"
                show-password
              />
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                size="large"
                class="login-button"
                :loading="registerLoading"
                @click="handleRegister"
              >
                注册
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <el-tab-pane label="管理员登录" name="admin">
          <el-form
            ref="adminFormRef"
            :model="adminForm"
            :rules="adminRules"
            label-width="0px"
            class="login-form"
          >
            <el-form-item prop="username">
              <el-input
                id="admin-username"
                name="username"
                v-model="adminForm.username"
                placeholder="请输入管理员用户名"
                size="large"
                prefix-icon="User"
              />
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                id="admin-password"
                name="password"
                v-model="adminForm.password"
                type="password"
                placeholder="请输入管理员密码"
                size="large"
                prefix-icon="Lock"
                show-password
              />
            </el-form-item>
            <el-form-item>
              <el-button
                type="danger"
                size="large"
                class="login-button"
                :loading="adminLoading"
                @click="handleAdminLogin"
              >
                管理员登录
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock, Message } from '@element-plus/icons-vue'
import api from '@/utils/axios'

const router = useRouter()
const activeTab = ref('login')
const loginFormRef = ref(null)
const registerFormRef = ref(null)
const adminFormRef = ref(null)
const loginLoading = ref(false)
const registerLoading = ref(false)
const adminLoading = ref(false)

const loginForm = reactive({
  email: '',
  password: ''
})

const registerForm = reactive({
  name: '',
  email: '',
  password: '',
  confirmPassword: ''
})

const adminForm = reactive({
  username: '',
  password: ''
})

const loginRules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ]
}

const registerRules = {
  name: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, message: '用户名长度不能少于2位', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

const adminRules = {
  username: [
    { required: true, message: '请输入管理员用户名', trigger: 'blur' },
    { min: 3, message: '用户名长度不能少于3位', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入管理员密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ]
}

function validateConfirmPassword(rule, value, callback) {
  if (value !== registerForm.password) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const handleLogin = async () => {
  if (!loginFormRef.value) return
  loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loginLoading.value = true
      try {
        const response = await api.post('/login', {
          email: loginForm.email,
          password: loginForm.password
        })
        
        if (response.success) {
          ElMessage.success('登录成功')
          // 保存token
          localStorage.setItem('token', response.data.token)
          localStorage.setItem('user', JSON.stringify(response.data.user))
          // 跳转到首页
          router.push('/home')
        } else {
          ElMessage.error(response.message || '登录失败')
        }
      } catch (error) {
        ElMessage.error('登录失败，请检查网络连接')
      } finally {
        loginLoading.value = false
      }
    }
  })
}

const handleRegister = async () => {
  if (!registerFormRef.value) return
  registerFormRef.value.validate(async (valid) => {
    if (valid) {
      registerLoading.value = true
      try {
        const response = await api.post('/register', {
          name: registerForm.name,
          email: registerForm.email,
          password: registerForm.password
        })
        
        if (response.success) {
          ElMessage.success('注册成功，请登录')
          // 切换到登录tab
          activeTab.value = 'login'
          // 清空注册表单
          registerForm.name = ''
          registerForm.email = ''
          registerForm.password = ''
          registerForm.confirmPassword = ''
        } else {
          ElMessage.error(response.message || '注册失败')
        }
      } catch (error) {
        ElMessage.error('注册失败，请检查网络连接')
      } finally {
        registerLoading.value = false
      }
    }
  })
}

const handleAdminLogin = async () => {
  if (!adminFormRef.value) return
  adminFormRef.value.validate(async (valid) => {
    if (valid) {
      adminLoading.value = true
      try {
        console.log('发送管理员登录请求:', {
          username: adminForm.username,
          password: adminForm.password
        })
        
        const response = await api.post('/admin/login', {
          username: adminForm.username,
          password: adminForm.password
        })
        
        console.log('管理员登录响应:', response)
        
        if (response.success) {
          ElMessage.success('管理员登录成功')
          localStorage.setItem('adminToken', response.data.token)
          localStorage.setItem('userType', 'admin')
          localStorage.setItem('adminUser', JSON.stringify(response.data.user))
          
          console.log('管理员登录成功，准备跳转到管理后台')
          console.log('存储的数据:', {
            adminToken: response.data.token,
            userType: 'admin',
            adminUser: response.data.user
          })
          
          // 验证token是否正确保存
          console.log('验证localStorage中的token:', localStorage.getItem('adminToken'))
          console.log('验证localStorage中的userType:', localStorage.getItem('userType'))
          
          // 跳转到前端管理后台
          setTimeout(() => {
            console.log('跳转到前端管理后台')
            router.push('/admin')
          }, 100)
        } else {
          ElMessage.error(response.message || '管理员登录失败')
        }
      } catch (error) {
        console.error('管理员登录错误:', error)
        ElMessage.error('管理员登录失败，请检查网络连接')
      } finally {
        adminLoading.value = false
      }
    }
  })
}

const handleTabClick = () => {
  // 切换tab时重置表单
  loginFormRef.value?.resetFields()
  registerFormRef.value?.resetFields()
  adminFormRef.value?.resetFields()
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  width: 100vw;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
  margin: 0;
  box-sizing: border-box;
}

.login-box {
  width: 100%;
  max-width: 500px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  padding: 50px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
}

.logo-section {
  text-align: center;
  margin-bottom: 30px;
}

.logo-section h1 {
  font-size: 32px;
  color: #1890ff;
  margin-bottom: 8px;
}

.logo-section p {
  color: #666;
  font-size: 14px;
}

.login-tabs {
  margin-top: 20px;
}

.login-form {
  margin-top: 20px;
}

.login-button {
  width: 100%;
  margin-top: 10px;
}

:deep(.el-tabs__item) {
  font-size: 16px;
  font-weight: 500;
}

:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #1890ff inset;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-container {
    padding: 10px;
  }
  
  .login-box {
    max-width: 100%;
    padding: 30px 20px;
    margin: 0;
  }
  
  .logo-section h1 {
    font-size: 28px;
  }
}

@media (max-width: 480px) {
  .login-box {
    padding: 20px 15px;
    border-radius: 12px;
  }
  
  .logo-section h1 {
    font-size: 24px;
  }
  
  .logo-section p {
    font-size: 12px;
  }
}
</style>

